package server;

import java.io.InputStream;
import java.net.Socket;
import java.util.List;
import java.util.Map;

public class RequestProcessor extends Thread {

    private Socket socket;
    private Map<String,HttpServlet> servletMap;
    private Mapper mapper;

    public RequestProcessor(Socket socket, Map<String, HttpServlet> servletMap, Mapper mapper) {
        this.socket = socket;
        this.servletMap = servletMap;
        this.mapper = mapper;
    }

    @Override
    public void run() {
        try{
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            // 静态资源处理
            if(servletMap.get(request.getUrl()) == null) {
                response.outputHtml(request.getUrl(), mapper);
            }else{
                // 动态资源servlet请求
                HttpServlet httpServlet = servletMap.get(request.getUrl());
                if(null == httpServlet)
                    return;
                httpServlet.service(request,response);
            }

            socket.close();

        }catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("finished request!");
    }


    private HttpServlet getHttpServlet(String url) {
        HttpServlet httpServlet = servletMap.get(url);
        if (httpServlet!=null){
            return httpServlet;
        }
        List<HostMapper> hosts = mapper.getHosts();
        if (hosts.isEmpty()){
            return null;
        }
        for (HostMapper host : hosts) {
            List<ContextMapper> contexts = host.getContexts();
            if (contexts.isEmpty()){
                continue;
            }
            for (ContextMapper context : contexts) {
                List<WrapperMapper> wrappers = context.getWrappers();
                if (wrappers.isEmpty()) {
                    continue;
                }
                for (WrapperMapper wrapper : wrappers) {
                    if (wrapper.getUrl().equalsIgnoreCase(url)){
                        return wrapper.getHttpServlet();
                    }
                }
            }
        }
        return null;
    }
}